<template>
    <div class="transfer-order-page">
        <!-- 页面标题与返回按钮 -->
        <div class="page-header">
            <h2>调拨单</h2>
            <el-button type="text" @click="handleBack">返回</el-button>
        </div>

        <!-- 搜索与操作区 -->
        <div class="search-bar">
            <el-input v-model="searchKeyword" placeholder="请输入关键词搜索" class="search-input" clearable />
            <el-button type="primary" class="search-btn" @click="handleSearch">
                查询
            </el-button>
            <el-button type="success" class="add-btn" @click="handleAddOrder">
                新增调拨单
            </el-button>
        </div>

        <!-- 调拨单表格 -->
        <el-table :data="filteredOrders" border stripe class="order-table" v-loading="loading">
            <el-table-column prop="transferTime" label="调拨时间" sortable />
            <el-table-column prop="orderNo" label="调拨单号" />
            <el-table-column prop="fromWarehouse" label="发货仓库" />
            <el-table-column prop="toWarehouse" label="收货仓库" />
            <el-table-column prop="productName" label="调拨产品" />
            <el-table-column prop="quantity" label="调拨数量" />
            <el-table-column label="状态">
                <template #default="scope">
                    <el-tag :type="scope.row.status === '已完成' ? 'success' : 'warning'">
                        {{ scope.row.status }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="description" label="附加说明" />
            <el-table-column label="操作" fixed="right" width="280">
                <template #default="scope">
                    <el-button type="primary"   @click="handleViewDetail(scope.row)">
                        明细
                    </el-button>
                    <el-button type="warning"   @click="handleEditOrder(scope.row)"
                        v-if="scope.row.status !== '已完成'">
                        编辑
                    </el-button>
                    <el-button type="danger"   @click="handleDeleteOrder(scope.row.id)"
                        v-if="scope.row.status !== '已完成'">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination">
            <span class="total-info">共 {{ totalOrders }} 条 共 {{ totalPages }} 页</span>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]"
                :total="totalOrders" layout="prev, pager, next, jumper, sizes" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 新增/编辑调拨单弹窗 -->
        <el-dialog 
            v-model="dialogVisible" 
            :title="isEditMode ? '编辑调拨单' : '新增调拨单'" 
            width="90%" 
            top="2vh"
            :before-close="handleDialogClose"
        >
            <!-- 调拨单基础信息 -->
            <div class="transfer-form-header" style="margin-bottom: 20px; display: flex; align-items: center; gap: 20px; flex-wrap: wrap;">
                <el-form-item label="调拨时间" style="margin-bottom: 0;">
                    <el-date-picker v-model="formData.transferTime" type="date" placeholder="选择日期" />
                </el-form-item>
                <el-form-item label="单据编号" style="margin-bottom: 0;">
                    <el-input v-model="formData.orderNo" placeholder="自动生成" disabled />
                </el-form-item>
                <el-form-item label="换入仓库" style="margin-bottom: 0;">
                    <el-select v-model="formData.toWarehouse" placeholder="请选择" :disabled="isEditMode">
                        <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.name" :value="warehouse.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="换出仓库" style="margin-bottom: 0;">
                    <el-select v-model="formData.fromWarehouse" placeholder="请选择" :disabled="isEditMode">
                        <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.name" :value="warehouse.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="经办人" style="margin-bottom: 0;">
                    <el-input v-model="formData.handler" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="备注" style="margin-bottom: 0; flex: 1; min-width: 200px;">
                    <el-input v-model="formData.description" placeholder="请输入备注" />
                </el-form-item>
            </div>

            <!-- 调拨商品明细 -->
            <div class="transfer-table-header" style="display: flex; align-items: center; margin-bottom: 10px;">
                <span>调拨商品明细</span>
                <el-button 
                    type="primary" 
                    icon="el-icon-plus" 
                    size="mini" 
                    style="margin-left: 10px; background-color: #10b981; border-color: #10b981;"
                    @click="addProductRow"
                >
                    添加
                </el-button>
            </div>

            <el-table 
                :data="formData.productRows" 
                border 
                size="small" 
                style="width: 100%;"
            >
                <el-table-column label="序号" type="index" width="60" align="center" />
                <el-table-column label="产品编号" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.productNo" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="产品名称" align="center">
                    <template #default="scope">
                        <el-select v-model="scope.row.productName" placeholder="请选择" @change="handleProductChange(scope.row)">
                            <el-option v-for="p in productList" :key="p.id" :label="p.name" :value="p.name" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="归属品牌" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.brand" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="规格" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.spec" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="类型" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.type" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="零售价" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.retailPrice" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="折扣" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.discount" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="折扣价" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.discountPrice" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="特价" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.specialPrice" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="秒杀价" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.seckillPrice" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="调出数量" align="center">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.quantity" type="number" min="1" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="仓库" align="center">
                    <template #default>
                        <el-input :value="formData.fromWarehouse" disabled />
                    </template>
                </el-table-column>
                <el-table-column label="库存" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.stock" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="总金额" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.totalAmount" placeholder="自动计算" />
                    </template>
                </el-table-column>
                <el-table-column label="备注" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.remark" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80" align="center">
                    <template #default="scope">
                        <el-button 
                            type="danger" 
                            icon="el-icon-delete" 
                            size="mini"
                            @click="removeProductRow(scope.row)"
                        />
                    </template>
                </el-table-column>
            </el-table>

            <!-- 底部按钮 -->
            <template #footer>
                <el-button @click="handleDialogClose">取消</el-button>
                <el-button type="primary" style="background-color: #10b981; border-color: #10b981;" @click="handleSaveOrder">
                    提交
                </el-button>
                <el-button type="success" @click="handleSaveAsDraft">
                    草稿
                </el-button>
            </template>
        </el-dialog>

        <!-- 明细弹窗 -->
        <el-dialog v-model="detailVisible" title="调拨单明细" width="500px">
            <el-descriptions column="1" border>
                <el-descriptions-item label="调拨单号">{{ currentOrder.orderNo }}</el-descriptions-item>
                <el-descriptions-item label="调拨时间">{{ currentOrder.transferTime }}</el-descriptions-item>
                <el-descriptions-item label="发货仓库">{{ currentOrder.fromWarehouse }}</el-descriptions-item>
                <el-descriptions-item label="收货仓库">{{ currentOrder.toWarehouse }}</el-descriptions-item>
                <el-descriptions-item label="调拨产品">{{ currentOrder.productName }}</el-descriptions-item>
                <el-descriptions-item label="调拨数量">{{ currentOrder.quantity }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                    <el-tag :type="currentOrder.status === '已完成' ? 'success' : 'warning'">
                        {{ currentOrder.status }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="附加说明">{{ currentOrder.description || '无' }}</el-descriptions-item>
            </el-descriptions>
        </el-dialog>

        <!-- 删除确认弹窗 -->
        <el-dialog v-model="deleteConfirmVisible" title="确认删除" width="300px">
            <p>确定要删除此调拨单吗？此操作不可撤销。</p>
            <template #footer>
                <el-button @click="deleteConfirmVisible = false">取消</el-button>
                <el-button type="danger" @click="confirmDelete">确认删除</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// 路由实例
const router = useRouter()

// 状态
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalOrders = ref(0)
const totalPages = ref(0)

const dialogVisible = ref(false)
const detailVisible = ref(false)
const deleteConfirmVisible = ref(false)
const isEditMode = ref(false)
const currentOrder = ref({})
const deleteOrderId = ref(null)
const formRef = ref(null)

// 仓库与产品数据（扩展产品信息用于自动填充）
const warehouseList = ref([
    { id: 1, name: '仓库1' },
    { id: 2, name: '仓库2' },
    { id: 3, name: '仓库3' }
])

const productList = ref([
    { id: 1, name: '兰蔻', brand: '兰蔻', spec: '50ml', type: '护肤品', retailPrice: '890' },
    { id: 2, name: '雅诗兰黛', brand: '雅诗兰黛', spec: '30ml', type: '护肤品', retailPrice: '690' },
    { id: 3, name: 'SK-II', brand: 'SK-II', spec: '230ml', type: '护肤品', retailPrice: '1540' }
])

// 表单数据（完整的商品行结构）
const formData = reactive({
    id: null,
    orderNo: '',
    transferTime: '',
    fromWarehouse: '',
    toWarehouse: '',
    handler: '',
    description: '',
    productRows: [] // 商品明细行数组
})

// 验证器
const checkWarehouse = (rule, value, callback) => {
    if (value && value === formData.fromWarehouse) {
        callback(new Error('发货仓库和收货仓库不能相同'))
    } else {
        callback()
    }
}

// 表单验证规则
const formRules = reactive({
    fromWarehouse: [{ required: true, message: '请选择发货仓库', trigger: 'change' }],
    toWarehouse: [
        { required: true, message: '请选择收货仓库', trigger: 'change' },
        { validator: checkWarehouse, trigger: 'change' }
    ]
})

// 示例数据
const transferOrders = ref([
    {
        id: 1,
        orderNo: 'EXC20231001',
        transferTime: '2023-10-01',
        fromWarehouse: '仓库1',
        toWarehouse: '仓库2',
        productName: '兰蔻',
        quantity: 10,
        status: '已完成',
        description: '无'
    },
    {
        id: 2,
        orderNo: 'EXC20231002',
        transferTime: '2023-10-02',
        fromWarehouse: '仓库2',
        toWarehouse: '仓库3',
        productName: '雅诗兰黛',
        quantity: 8,
        status: '进行中',
        description: '加急'
    }
])

// 过滤 + 分页
const filteredOrders = computed(() => {
    const keyword = searchKeyword.value.trim().toLowerCase()
    let result = transferOrders.value.filter(o =>
        [o.orderNo, o.fromWarehouse, o.toWarehouse, o.productName, o.status]
            .some(v => v.toLowerCase().includes(keyword))
    )
    totalOrders.value = result.length
    totalPages.value = Math.ceil(result.length / pageSize.value)
    const start = (currentPage.value - 1) * pageSize.value
    return result.slice(start, start + pageSize.value)
})

// 方法们
const handleBack = () => router.back()
const handleSearch = () => currentPage.value = 1

// 新增调拨单：初始化商品行
const handleAddOrder = () => {
    isEditMode.value = false
    Object.assign(formData, {
        id: null, 
        orderNo: '', 
        transferTime: new Date().toISOString().split('T')[0], // 默认当前日期
        fromWarehouse: '',
        toWarehouse: '', 
        handler: '',
        description: '',
        productRows: []
    })
    // 默认添加一行商品
    addProductRow()
    dialogVisible.value = true
}

const handleEditOrder = row => {
    isEditMode.value = true
    // 模拟编辑时的商品行数据
    formData.productRows = [{
        productNo: 'P' + row.id,
        productName: row.productName,
        quantity: row.quantity,
        remark: row.description
    }]
    Object.assign(formData, { ...row })
    dialogVisible.value = true
}

const handleViewDetail = row => {
    currentOrder.value = { ...row }
    detailVisible.value = true
}

const handleDeleteOrder = id => {
    deleteOrderId.value = id
    deleteConfirmVisible.value = true
}

const confirmDelete = () => {
    transferOrders.value = transferOrders.value.filter(o => o.id !== deleteOrderId.value)
    deleteConfirmVisible.value = false
    ElMessage.success('调拨单已删除')
}

// 添加商品行
const addProductRow = () => {
    formData.productRows.push({
        productNo: '',
        productName: '',
        brand: '',
        spec: '',
        type: '',
        retailPrice: '',
        discount: '',
        discountPrice: '',
        specialPrice: '',
        seckillPrice: '',
        quantity: 1,
        stock: '',
        totalAmount: '',
        remark: ''
    })
}

// 删除商品行
const removeProductRow = (row) => {
    formData.productRows = formData.productRows.filter(item => item !== row)
}

// 选择产品时自动填充基础信息
const handleProductChange = (row) => {
    const product = productList.value.find(p => p.name === row.productName)
    if (product) {
        row.brand = product.brand
        row.spec = product.spec
        row.type = product.type
        row.retailPrice = product.retailPrice
    }
}

// 保存为草稿
const handleSaveAsDraft = () => {
    ElMessage.success('已保存为草稿')
    dialogVisible.value = false
}

// 保存调拨单
const handleSaveOrder = () => {
    if (formData.productRows.length === 0) {
        ElMessage.error('请至少添加一个调拨商品')
        return
    }
    if (!formData.fromWarehouse || !formData.toWarehouse) {
        ElMessage.error('请选择出入库仓库')
        return
    }

    if (isEditMode.value) {
        const i = transferOrders.value.findIndex(o => o.id === formData.id)
        if (i !== -1) transferOrders.value[i] = { ...formData }
        ElMessage.success('调拨单已更新')
    } else {
        const newId = (Math.max(0, ...transferOrders.value.map(o => o.id)) + 1)
        transferOrders.value.unshift({
            ...formData,
            id: newId,
            orderNo: `EXC${new Date().getFullYear()}${(new Date().getMonth() + 1).toString().padStart(2, '0')}${newId.toString().padStart(3, '0')}`,
            status: '进行中',
            // 取第一个商品作为列表显示的产品名称
            productName: formData.productRows[0].productName || '多种商品',
            quantity: formData.productRows.reduce((sum, item) => sum + (item.quantity || 0), 0)
        })
        ElMessage.success('调拨单已创建')
    }
    dialogVisible.value = false
}

const handleDialogClose = () => {
    dialogVisible.value = false
}

const handleSizeChange = val => {
    pageSize.value = val
    currentPage.value = 1
}
const handleCurrentChange = val => currentPage.value = val
</script>

<style scoped>
.transfer-order-page {
    padding: 20px;
    background: #fff;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.search-bar {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 20px;
}

.search-input {
    width: 300px;
}

.add-btn {
    margin-left: auto;
}

.pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16px;
}

.total-info {
    color: #666;
    font-size: 14px;
}
</style>